//---------------------------------------------------------------------------

#pragma hdrstop

#include "DataBase.h"
#include "PublicConst.h"

using namespace std;
//---------------------------------------------------------------------------

const String INSERT_INTO_BOOKMARKS = 
    "insert into BookMarks (Name, URL) "
    " values ('%s', '%s') ;";

DataBase::DataBase()
{
	Init();
}

DataBase::~DataBase()
{

}
void DataBase::Init()
{
	curDB.open(DEFAULT_DB.c_str());
}

void DataBase::Close()
{
	curDB.close();
}
DataBase* DataBase::GetCurrentDB()
{
	if (NULL == DB)
	{
		DB = new DataBase();
	}
	return DB;
}

void DataBase::SaveURLInfo(const URLInfo &URL)
{
    String sql;
    sql.sprintf(INSERT_INTO_BOOKMARKS.c_str(), URL.fileName.c_str(), URL.url.c_str());
    curDB.execDML(sql.c_str());
}

void DataBase::SaveURLsInfo(const std::list<URLInfo> &URLs)
{
    String sql;
    curDB.execDML(TEXT("BEGIN TRANSACTION;"));
    list<URLInfo>::const_iterator it = URLs.begin();
    for (; it != URLs.end(); ++it)
    {
        sql.sprintf(INSERT_INTO_BOOKMARKS.c_str(), it->fileName.c_str(), it->url.c_str());
        curDB.execDML(sql.c_str());    
    }

    curDB.execDML(TEXT("COMMIT TRANSACTION;"));
        
}

void DataBase::GetBookMarks(list<Bookmark> &bookmarks)
{
    CppSQLite3Query qurey = curDB.execQuery(TEXT("select ID,Name,URL from Bookmarks ;"));

    Bookmark mark;
    while (!qurey.eof())
    {
        mark.ID = qurey.getIntField(TEXT("ID"));
        mark.urlInfo.fileName = ExtractFileName(qurey.fieldValue(TEXT("Name")));
        mark.urlInfo.url = qurey.fieldValue(TEXT("URL"));
        
        bookmarks.push_back(mark);
        qurey.nextRow();
    }
}

void DataBase::DeleteBookMarksByID(const list<int> &IDList)
{
    String IDCondition;
    list<int>::const_iterator it = IDList.begin();
    for (; it != IDList.end(); ++it)
    {
        IDCondition += String(*it) + ",";        
    }
    IDCondition.SetLength(IDCondition.Length() - 1);

    String sql;
    sql.sprintf(TEXT("delete from Bookmarks where ID in (%s) ;"), IDCondition.c_str());

    curDB.execDML(sql.c_str());

}


#pragma package(smart_init)
